import {UploadOutlined, DownloadOutlined} from '@ant-design/icons';
import {Button, Divider, message, Input, Popconfirm, Upload, Select, Tabs} from 'antd';
import React, {useState, useRef, useEffect} from 'react';
import {PageContainer, FooterToolbar} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import styles from '../../../global.less';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  getPayOrder,
  BackOrder,
  BackOrderByWechat,
  storeList,
  exportOrderByStores,
  storeBaseList,
  rectifyIntegral
} from './service';
import OrderCommon from '@/pages/OrderCommon';
import defaultSetting from '@/../config/defaultSettings';
import {money_trans, saveFileAs} from '@/utils/utils';
import {query} from '@/services/user';
import moment from 'moment';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({...fields});
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  const hide = message.loading('正在配置');

  try {
    await updateRule({
      name: fields.name,
      desc: fields.desc,
      key: fields.key,
    });
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const {TabPane} = Tabs;
const TableList = (props) => {
  const returnCountRef = useRef();
  const [order, setOrder] = useState(false);
  const [recordLoading, setRecordLoading] = useState(false);
  const [rechargeLoading, setRechargeLoading] = useState(false);
  const [count, setCount] = useState();
  const [payOrderValues, setPayOrderValues] = useState({});
  const actionRef = useRef();
  const [memberNum, setMemberNum] = useState();
  const [details, setDetails] = useState();
  const [giftUpload, setGiftUpload] = useState(false);
  const [isGift, setIsGift] = useState(true);
  const [storeArray, setStoreArray] = useState([]);
  const [outModal, handleOutModal] = useState(false);
  const [tabsState, setTabsState] = useState("1");
  const [exportRecords, setExportRecords] = useState(false);
  useEffect(() => {
    const {query} = props.history.location;
    setTimeout(() => {
      getStore();
      return query?.cardNum
        ? (setMemberNum(query?.cardNum), setTabsState(query?.type))
        : (setMemberNum(), setTabsState(tabsState));
    }, 0);
    actionRef.current.reload();
  }, [props.history.location.query?.cardNum]);
  const getStore = () => {
    storeBaseList()
      .then((res) => {
        const {code} = res;
        code === 0 ? setStoreArray(res.data) : message.info(res.message);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const uploadOnChange = (info, exact) => {
    if (exact === 'record') {
      setRecordLoading(true);
    } else {
      setRechargeLoading(true);
    }
    if (info.file.status === 'done') {
      if (exact === 'record') {
        setRecordLoading(false);
      } else {
        setRechargeLoading(false);
      }
      actionRef.current.reload();
      const {
        file: {
          response: {code, message: mes},
        },
      } = info;
      if (code !== 0) {
        message.error(mes);
      } else {
        message.success('导入成功');
      }
    } else {
      // message.error('导入失败请重试！');
    }
  };
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const {code, data} = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const handleBack = (params, payload) => {
    params.orderId = details.id;
    params.memberNumber = details.memberNumber;
    params.storeId = payload.storeId;
    params.refundOrderDetails = [
      {
        count: returnCountRef.current,
        orderDetailId: payload.id,
      },
    ];
    delete params.memberId;
    delete params.orderDetailId;
    BackOrder(params)
      .then((res) => {
        const {code} = res;
        if (code === 0) {
          return params.refundType === 1
            ? message.success('退货退款成功!')
            : message.success('退款成功!');
        } else {
          message.info(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleBackByWechat = (params, payload) => {
    params.orderId = details.id;
    params.memberNumber = details.memberNumber;
    params.storeId = payload.storeId;
    params.refundOrderDetails = [
      {
        count: returnCountRef.current,
        orderDetailId: payload.id,
      },
    ];
    delete params.memberId;
    delete params.orderDetailId;
    BackOrderByWechat(params)
      .then((res) => {
        const {code} = res;
        if (code === 0) {
          return params.refundType === 1
            ? message.success('退货退款成功!')
            : message.success('退款成功!');
        } else {
          message.info(res.message);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const callback = async (e) => {
    await setTabsState(e);
    await actionRef.current.reload();
  };
  const handleIsGift = () => {
    setGiftUpload(true);
  };
  const isGiftChange = (e) => {
    setIsGift(e);
  };

  const columns = [
    {
      title: '订单编号',
      dataIndex: 'number',
      valueType: 'text',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '上游订单号',
      dataIndex: 'upperNumber',
      valueType: 'text',
    },
    {
      title: '订单店铺',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        if (record.childrenRecord && record.childrenRecord[0]) {
          return <div>{record.childrenRecord ? record.childrenRecord[0].storeName : ''}</div>;
        } else {
          return <div>{''}</div>;
        }
      },
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      valueType: 'text',
      renderFormItem: () => {
        return <Input allowClear onChange={(e) => setMemberNum(e.target.value)}/>;
      },
    },
    {
      title: '会员姓名',
      dataIndex: 'memberName',
      valueType: 'text',
    },
    {
      title: '订单商品',
      dataIndex: 'goodsItem',
      valueType: 'text',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <div>{record.childrenRecord ? record.childrenRecord[0]?.goodsItemName.replace('充值','消费') + '...' : ''}</div>
        );
      },
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        0: {
          text: '未支付',
          status: 'Default',
        },
        1: {
          text: '支付中',
          status: 'Processing',
        },
        2: {
          text: '支付成功',
          status: 'Success',
        },
        3: {
          text: '支付失败',
          status: 'Error',
        },
      },
    },
    {
      title: '退款状态',
      dataIndex: 'refundStatus',
      hideInForm: true,
      hideInTable:true,
      valueEnum: {
        0: {
          text: '未退款',
          status: 'Default',
        },
        1: {
          text: '退款中',
          status: 'Processing',
        },
        2: {
          text: '退款成功',
          status: 'Success',
        },
        3: {
          text: '退款失败',
          status: 'Error',
        },
        4: {
          text: '取消退款',
          status: 'Error',
        },
      },
    },
    {
      title: '订单类型',
      dataIndex: 'subType',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        1: {
          text: '消费商品',
          status: 'Error',
        },
        2: {
          text: '会员消费',
          status: 'Processing',
        },
        3: {
          text: '会员开卡',
          status: 'Success',
        },
      },
    },

    {
      title: '订单总金额',
      dataIndex: 'totalAmount',
      valueType: 'text',
      hideInSearch: true,
      render: (dom, entity) => {
        return money_trans(dom, true);
      },
    },
    {
      title: '是否赠送',
      dataIndex: 'isGift',
      hideInTable: true,
      hideInSearch: true,
      valueEnum: {
        true: {
          text: '是',
          status: 'Success',
        },
        false: {
          text: '否',
          status: 'Error',
        },
      },
    },
    {
      title: '支付方式',
      dataIndex: 'payType',
      valueEnum: {
        1: {
          text: '现金支付',
          status: 'Processing',
        },
        2: {
          text: '刷卡支付',
          status: 'Success',
        },
        3: {
          text: '扫码支付',
          status: 'Error',
        },
        4: {
          text: '余额支付',
          status: 'Error',
        },
        5: {
          text: '积分支付',
          status: 'Error',
        },
        9: {
          text: '微信支付',
          status: 'Success',
        },
      },
      render: (_, record) => {
        if (record.payType === 5 && record.isCompose){
          return <>组合支付</>;
        }else{
          return _;
        }
      },
    },

    {
      title: '销售人员',
      dataIndex: 'sellerName',
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      valueType: 'dateRange',
      render: (_, record) => {
        if (record.payTime) {
          return new Date(record.payTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startPayTime: value[0],
            endPayTime: value[1],
          };
        },
      },
    },
    {
      title: '下单时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      initialValue: [moment().subtract(3,'d').format("YYYY-MM-DD"),moment().add(1,'d').format("YYYY-MM-DD")],
      render: (_, record) => {
        if (record.createTime) {
          return new Date(record.createTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '消费店铺',
      // hideInSearch: true,
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
            placeholder="请选择消费店铺"
            showSearch
            filterOption={(input, option) => {
                if (option.options){
                  option.options.map((data=>{
                    return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                  }))
                  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }else {
                  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }
              }
            }
            mode="multiple"
            allowClear
          >
            {
              storeArray.map((item_, index) => {
              return (
                <Select.OptGroup label={item_.posName} key={item_.posName}>
                  {
                    item_.stores.map((item_s, index_s) => {
                      return (
                        <Select.Option value={item_s.id} key={item_s.id} >
                          {item_s.name}
                        </Select.Option>
                      );
                    })
                  }
                </Select.OptGroup>
              );
            })}
          </Select>
        );
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: tabsState == 2 ? 160 : 80,
      render: (_, record) => [
        <>
          <Access accessKey={"@showOrderDetails"}>
            <a
              onClick={() => {
                handlePay(record.id);
                setDetails(record);
              }}
            >
              查看
            </a>
          </Access>
          {
            record.type === 2 && record.refundStatus === 2 ?(
              <>
                <Access accessKey={"@rectifyIntegral"}>

                </Access>
                <Divider type="vertical"/>
                <Popconfirm
                  placement="top"
                  title="确定要扣除积分吗?"
                  onConfirm={() => {
                    rectifyIntegral({
                      id:record.id
                    }).then(res=>{
                      if (res && res.code === 0){
                        message.success('冲正成功');
                      }
                    })
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <a>积分冲正</a>
                </Popconfirm>
              </>
            ):null
          }

        </>,
      ],
    },
  ];
  const outColumns = [
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      valueType: 'text',
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '未支付',
          status: 'Default',
        },
        1: {
          text: '支付中',
          status: 'Processing',
        },
        2: {
          text: '支付成功',
          status: 'Success',
        },
        3: {
          text: '支付失败',
          status: 'Error',
        },
      },
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      valueType: 'dateRange',
      render: (_, record) => {
        if (record.payTime) {
          return new Date(record.payTime).toLocaleString();
        } else {
          return '-';
        }
      },
      search: {
        transform: (value) => {
          return {
            startPayTime: value[0],
            endPayTime: value[1],
          };
        },
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '支付时间为必选项',
          },
        ],
      },
    },
    {
      title: '消费店铺',
      // hideInSearch: true,
      dataIndex: 'storeIds',
      hideInTable: true,
      renderFormItem: (item, {defaultRender, ...rest}, form) => {
        return (
          <Select
        placeholder="请选择消费店铺"
        showSearch
        filterOption={(input, option) => {
          if (option.options){
            option.options.map((data=>{
              return data.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            }))
            return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
          }else {
            return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
          }
        }
      }
        mode="multiple"
        allowClear
        >
        {
          storeArray.map((item_, index) => {
            return (
              <Select.OptGroup label={item_.posName}>
                {
                  item_.stores.map((item_s, index_s) => {
                    return (
                      <Select.Option value={item_s.id} key={item_s.id} >
                        {item_s.name}
                      </Select.Option>
                    );
                  })
                }
              </Select.OptGroup>
            );
          })}
      </Select>
        );
      },
    },
  ];
  const payRef = (payload) => {
    const params = {
      memberId: details.memberId,
      orderDetailId: payload.id,
    };
    const popFim = (
      <div key="popFim" style={{display: 'flex', justifyContent: 'space-between', alignContent: 'center'}}>
        <div>退货数量:</div>
        <Input
          placeholder="输入退货数量"
          style={{width: 140, height: 30, marginLeft: 10}}
          onChange={(e) => {
            return (returnCountRef.current = e.target.value);
          }}
        />
      </div>
    );
    return (
      <>
        {details.type === 1 ? (
          <>
            <Access accessKey={"@refundConsumerOrder"}>
              <Popconfirm
                icon={null}
                okText="确认"
                cancelText="取消"
                title={popFim}
                onConfirm={() => {
                  params.refundType = 1;
                  if (payload.payType === 9){
                    returnCountRef.current > payload.count ? message.warning('退货数量不能超过订单数量!') : handleBackByWechat(params, payload);
                  }else{
                    returnCountRef.current > payload.count ? message.warning('退货数量不能超过订单数量!') : handleBack(params, payload);
                  }
                }}
              >
                <a>退货退款</a>
              </Popconfirm>
              <Divider type="vertical"/>
            </Access>

          </>
        ) : (payload.goodsId === null?
            <>
              <Access accessKey={"@refundRechargeOrder"}>
                <Popconfirm
                  icon={null}
                  okText="确认"
                  cancelText="取消"
                  title={popFim}
                  onConfirm={() => {
                    params.refundType = 2;
                    if (!details.memberNumber) {
                      return message.warn('非会员暂无仅退款功能!');
                    }
                    if (payload.payType === 9){
                      returnCountRef.current > payload.count ? message.warning('退款数量不能超过订单数量!') : handleBackByWechat(params, payload);
                    }else{
                      returnCountRef.current > payload.count ? message.warning('退款数量不能超过订单数量!') : handleBack(params, payload);
                    }
                  }}
                >
                  <a>充值退款</a>
                </Popconfirm>
              </Access>

          </>:null
        )}
      </>
    );
  };

  return (
    <PageContainer>
      <Tabs
        activeKey={tabsState}
        onChange={callback}
        style={{background: 'white', paddingLeft: 10}}
      >
        <Tabs.TabPane tab="消费商品" key="1"></Tabs.TabPane>
        <Tabs.TabPane tab="会员消费" key="2"></Tabs.TabPane>
      </Tabs>
      <ProTable
        headerTitle="订单列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{x: 1200}}
        bordered
        footer={(record) => {
          let num =
            record.length > 0
              ? record.reduce((c, item) => {
                return c + Number(item.totalAmount);
              }, 0)
              : 0;
          return (
            <div key="orderListTableFooter">
              <span>合计：</span>
              <a>{Number(num).toFixed(2)}</a>
            </div>
          );
        }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => {
          switch (Number(tabsState)) {
            case 1:
              return (
                <div >
                  <Access accessKey={"@exportConsumerOrder"}>
                    <Button
                      key="toolBarRender1"
                      loading={exportRecords}
                      onClick={() => {
                        handleOutModal(true);
                        setExportRecords(true);
                      }}
                      type="dashed"
                      danger
                      icon={<UploadOutlined/>}
                    >
                      导出消费单
                    </Button>
                  </Access>

                </div>
              );
            case 2:
              return (
                <div >
                  <Access accessKey={"@exportRechargeOrder"}>
                    <Button
                      key="toolBarRender2"
                      onClick={() => {
                        handleOutModal(true);
                        setExportRecords(true);
                      }}
                      loading={exportRecords}
                      danger
                      icon={<UploadOutlined/>}
                    >
                      导出充值单
                    </Button>
                  </Access>
                </div>
              );
            default:
              break;
          }
        }}
        request={(params, sorter, filter) => {
          if (tabsState) {
            params.type = tabsState;
            return queryRule({...params, sorter, filter, memberNumber: memberNum});
          }
        }}
        postData={(params) => {
          const {list, total} = params;
          list.map((item) => {
            item.childrenRecord = JSON.parse(JSON.stringify(item.children));
            delete item.children;
          });
          setCount(total);
          return list || [];
        }}
        onReset={(params) => {
          if (props.history.location.query?.type) {
            setTabsState(props.history.location.query?.type);
          }
          props.history.replace({cardNum: '', type: ''}, props.history.location);
          setMemberNum();
          setTimeout(() => {
            actionRef.current.reload();
          }, 0);
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm width={1300} onCancel={() => setOrder(false)} modalVisible={order} footer={null}>
        <OrderCommon
          payOrderValues={payOrderValues}
          refund={
            details
              ? details.status === 0 ||
              details.status === 1 ||
              details.status === 3 ||
              tabsState === 3
              ? null
              : payRef
              : null
          }
        />
      </CreateForm>
      <CreateForm
        title={'导出信息'}
        width={800}
        footer={null}
        onCancel={() => {
          handleOutModal(false);
          setExportRecords(false);
        }}
        modalVisible={outModal}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={(value) => {
            handleOutModal(false);
            let name;
            switch (Number(tabsState)) {
              case 1:
                name = '消费';
                break;
              case 2:
                name = '充值';
                break;
              case 3:
                name = '开卡';
                break;
              default:
                break;
            }
            value.type = tabsState;
            value.startPayTime = value.startPayTime + ' 00:00:00';
            value.endPayTime = value.endPayTime + ' 23:59:59';
            exportOrderByStores(value).then((res) => {
              if (res) {
                saveFileAs(res, name);
              }
              setExportRecords(false);
            });
          }}
          bordered
          type="form"
          columns={outColumns}
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: {span: 8},
            wrapperCol: {span: 24},
          }}
        />
      </CreateForm>

    </PageContainer>
  );
};

export default TableList;
